package com.xiaoran.commonapi.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtil {

    private final StringRedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);

    public void set(String key, String val, Integer expire_time) {
        if (expire_time < 0) {
            log.error(key, "写入的expiretime为负数", expire_time);
            return;
        }
        redisTemplate.opsForValue().set(key, val, expire_time, TimeUnit.SECONDS);
    }

    public boolean isExpireOrExists(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public String get(String key) {
        return Objects.requireNonNull(redisTemplate.opsForValue().get(key)).toString();
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    public void addVal(String key, Integer inc) {
        Integer val = Integer.parseInt(get(key)) + inc;
        set(key, String.valueOf(val), getExpire(key).intValue());
    }
}
